from ast import main
import logging
import threading
import time
from control.ControlManager import ControlManager
from core import LOGGER,callback,event,runningEvent
import modbus
import monitor.uip
import monitor.channel
from modbus.ModbusManager import ModbusManager 
from monitor.MonitorManager import MonitorManager
### 电池管理主入口  林恩德  2022.6.18
### 实现对电池状态的监测、分析，充放电控制，故障诊断与保护功能

class  BatteryManager:

    def on_monitor_datareceived(self,resouce,event,payload):
        LOGGER.debug("{}".format(payload))
        self.modbus.updateMonitorState(payload['type'],payload['data'])
        pass

    def __init__(self):
        self.modbus =  ModbusManager(manager=self)
        self.monitor = MonitorManager(manager=self)
        self.control = ControlManager(manager = self)
        callback.getInstance().subscribe(self.on_monitor_datareceived,self.monitor,event.MONITOR_DATA_CHANGED)
        self.running = True
    def run(self):
        LOGGER.info(msg="电池管理系统启动中")
        self.modbus.start()
        self.monitor.start()
        runningEvent.wait()
        LOGGER.info(msg="电池管理系统退出运行")
        #while (runningEvent.isSet()):#self.running):           
        #    time.sleep(0.1)
    

if __name__ == '__main__':
    LOGGER.setLevel(logging.DEBUG)  
    bms = BatteryManager()
    try:
        bms.run()
    except KeyboardInterrupt:  #  当按下Ctrl+C时，将执行destroy()子程序。
        runningEvent.set()
        
    